package servlet;

import model.DBUtil;
import model.Job;
import model.Puser;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;

@WebServlet("/xiugai")
public class xiugai extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        HttpSession session = req.getSession();
        Puser currentUser = (Puser) session.getAttribute("pcurrentUser");
        Integer puid = currentUser.puid;
        PrintWriter out = resp.getWriter();
        if (puid == null) {
            out.print("<script language='javascript'>alert('Wrong password. Login again!!'");
            return;
        }
        String jid = req.getParameter("jid");
        String title = req.getParameter("title");
        String type = req.getParameter("type");
        String salary = req.getParameter("salary");
        String contents = req.getParameter("contents");
        System.out.println(jid);
        System.out.println(title);
        System.out.println(type);
        System.out.println(salary);
        System.out.println(contents);
        Job job;
        try {
            job = sava(jid, title, type, salary, contents);
            resp.sendRedirect("/");
        } catch (SQLException throwable) {
            throwable.printStackTrace();
        }

    }

    public static Job sava(String jid, String title, String type, String salary, String contents) throws SQLException {
        try (Connection c = DBUtil.getConnection()) {
            String sql = "UPDATE job SET title=? ,type =?,salary =?,contents =?WHERE jid =?";
            try (PreparedStatement s = c.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS)) {
                s.setString(1, title);
                s.setString(2, type);
                s.setString(3, salary);
                s.setString(4, contents);
                s.setString(5,jid );
                s.executeUpdate();

            }
        }
        return null;
    }
}


